package com.edu.controller;

import com.edu.dao.ProductCategoryMapper;
import com.edu.dao.ProductMapper;
import com.edu.data.*;
import com.edu.service.Impl.OrderServiceImpl;
import com.edu.service.OrderService;
import com.edu.util.MyBatisUtil;
import org.apache.ibatis.session.SqlSession;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.ServletException;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.sql.SQLException;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

@Controller
@RequestMapping("/product")
public class ProductController {
    SqlSession sqlSession= MyBatisUtil.createSession();
    ProductMapper productMapper=sqlSession.getMapper(ProductMapper.class);
    ProductCategoryMapper productCategoryMapper=sqlSession.getMapper(ProductCategoryMapper.class);

    @Autowired
    OrderServiceImpl orderService;

    @RequestMapping("/toProduct")
    private void toProduct(HttpServletRequest req, HttpServletResponse resp) throws SQLException, ServletException, IOException {
        List<ProductCategory> productCategories = productCategoryMapper.getCategories(null);//根据父ID查询所有子商品分类
        req.setAttribute("categories",productCategories);
        req.setAttribute("products",productMapper.getProductsByCategoryLevelTwo(null,null));
        req.getRequestDispatcher("../static/manage/product.jsp").forward(req,resp);
    }

    @RequestMapping("/readProduct")
    private void readProduct(HttpServletRequest req, HttpServletResponse resp) throws SQLException, ServletException, IOException {
        Product product = productMapper.findProductById(Long.parseLong(req.getParameter("entityId")));
        req.setAttribute("entityId", product.getEpId());
        req.setAttribute("name", product.getEpName());
        req.setAttribute("description",product.getEpDescription());
        req.setAttribute("price", product.getEpPrice());
        req.setAttribute("stock", product.getEpStock());
        List<ProductCategory> categories = productCategoryMapper.getCategories(null);
        req.setAttribute("categories",categories);
        req.getRequestDispatcher("../static/manage/product-modify.jsp").forward(req,resp);
    }

    @RequestMapping("/delProduct")
    private void delProduct(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException {
        productMapper.deleteByid(Integer.parseInt(req.getParameter("entityId")));
        resp.sendRedirect("toProduct");
    }

    @RequestMapping("/selectProduct")
    private void selectProduct(HttpServletRequest req, HttpServletResponse resp) throws SQLException, IOException, ServletException {
        String fileName = req.getParameter("fileName");//商品名
        String category = req.getParameter("category");//商品分类
        List<Product> product = productMapper.findProduct(fileName,productCategoryMapper.findCategoryEpcId(category));
        req.setAttribute("products",product);
        List<ProductCategory> productCategories = productCategoryMapper.getCategories(null);//根据父ID查询所有子商品分类
        req.setAttribute("categories",productCategories);
        System.out.println(productCategoryMapper.findCategoryEpcId(category));
        req.setAttribute("category",category);
        req.setAttribute("fileName",fileName);
        req.getRequestDispatcher("../static/manage/product.jsp").forward(req,resp);
    }

    @RequestMapping("/createProduct")
    private void createProduct(HttpServletRequest req,HttpServletResponse resp) throws SQLException, ServletException, IOException {
        List<ProductCategory> productCategories = productCategoryMapper.getCategories(null);//根据父ID查询所有子商品分类
        req.setAttribute("categories", productCategories);
        if (productCategories.size() > 0)
            req.setAttribute("parentId", productCategories.get(0).getEpcId());
        req.getRequestDispatcher("../static/manage/product-modify.jsp").forward(req,resp);
    }

    @RequestMapping("/productView")
    private String productView(HttpServletRequest request,HttpServletResponse response) throws SQLException {
        prepareCategories(request);
        String entityId=request.getParameter("entityId");
        Product nowproduct = productMapper.getProducts(Long.parseLong(entityId));
        request.setAttribute("nowproduct",nowproduct);
        prepareRecentViewProducts(request,response,entityId);
        return "product-view";
    }

    @RequestMapping("/addProduct")
    private String addProduct(HttpServletRequest req,HttpServletResponse response){
        String idStr=req.getParameter("entityId");
        String quantityStr = req.getParameter("quantity");
        long quantity = 1;
        if(quantityStr!=null){
            quantity=Long.parseLong(quantityStr);
        }
        long enId=0;
        if(idStr!=null){
            enId=Long.parseLong(idStr);
        }
        Product product=productMapper.getProducts(enId);
        ShoppingCart cart=getCartFromSession(req);
        cart.addItem(product,quantity);
        req.setAttribute("msg","已经添加到购物车！");
        return "shopping-put";
    }

    @RequestMapping("/productList")
    private String productList(HttpServletRequest request){
        getCartFromSession(request);
        return "shopping";
    }

    @RequestMapping("/toAddress")
    private String toAddress(HttpServletRequest req){
        User users=(User) req.getSession().getAttribute("loginUser");
        if (users==null){
            return "login";
        }else {
            String address=users.getEuAddress();
            String[] addressArr=address.split(";");
            req.setAttribute("address",addressArr);
            return "address";
        }
    }

    @RequestMapping("/payProduct")
    private String payProduct(HttpServletRequest req) throws SQLException {
        ShoppingCart cart = (ShoppingCart) req.getSession().getAttribute("cart");
        User users = (User) req.getSession().getAttribute("loginUser");
        if (users==null){
            return "login";
        }else {
            String address=req.getParameter("address");
            orderService.payshoppingCart(cart,users,address);
            req.getSession().removeAttribute("cart");
            req.setAttribute("msg","恭喜！购买成功");
            return "shopping-put";
        }
    }

    @RequestMapping("/modProduct")
    private void modProduct(HttpServletRequest request,HttpServletResponse response) throws IOException {
        String idStr=request.getParameter("entityId");
        String quantityStr=request.getParameter("quantity");
        String indexStr=request.getParameter("index");
        long quantity = 1;
        if (!(quantityStr).trim().isEmpty())
            quantity = Long.parseLong(quantityStr);
        ShoppingCart cart = getCartFromSession(request);
        long index = 0;
        if (indexStr!=null){
            index=Long.parseLong(indexStr);
        }
        cart.modifyQuantity((int)index,quantity);
        response.sendRedirect("productList");
    }

    @RequestMapping("/removeProduct")
    private void remove(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String quantityStr = req.getParameter("quantity");
        long quantity=1;
        if (quantityStr!=null && quantityStr.length()>0)
            quantity = Long.parseLong(quantityStr);
        String indexStr = req.getParameter("index");
        ShoppingCart cart = getCartFromSession(req);
        cart.getItems().remove(Integer.parseInt(indexStr));
        resp.sendRedirect("productList");
    }

    private ShoppingCart getCartFromSession(HttpServletRequest request){
        HttpSession session=request.getSession();
        ShoppingCart cart = (ShoppingCart) session.getAttribute("cart");

        double total=0;
        for (int i=0;cart!=null && i<cart.getItems().size();i++){
            ShoppingCartItem item=cart.getItems().get(i);
            total=total+item.getCost();
        }
        if (cart==null){
            cart=new ShoppingCart();
        }
        session.setAttribute("cart",cart);
        request.setAttribute("total",total);
        return cart;
    }

    private void prepareCategories(HttpServletRequest request) throws SQLException{
        List<ProductCategory> categories = productCategoryMapper.getCategories(null);
        request.setAttribute("categories",categories);
    }

    private void prepareRecentViewProducts(HttpServletRequest request,HttpServletResponse response,String entityId) throws SQLException {
        Cookie[] cookies=request.getCookies();
        Cookie recentViewProductCookie=null;

        for (int i=0;i<cookies.length;i++){
            if (cookies[i].getName().equals("recentViewProducts")){
                recentViewProductCookie=cookies[i];
            }
        }

        String recents="";
        if (recentViewProductCookie!=null){
            String value=recentViewProductCookie.getValue();
            recents=value+"#"+entityId;
            recentViewProductCookie.setValue(recents);
            recentViewProductCookie.setPath("/");
        }else {
            recentViewProductCookie=new Cookie("recentViewProducts",entityId);
            recentViewProductCookie.setMaxAge(7*24*60*60);
            recentViewProductCookie.setPath("/");
        }
        response.addCookie(recentViewProductCookie);

        List<Product> productList=new ArrayList<>();
        if (recentViewProductCookie!=null){
            String value=recentViewProductCookie.getValue();
            if (value.indexOf("#")>0){
                String ids[]=value.split("#");
                Set<String> set=new HashSet<>();
                for (String id:ids){
                    set.add(id);
                }

                for (String id:set){
                    long idNum=0;
                    if (id!=null){
                        idNum=Long.parseLong(id);
                        productList.add(productMapper.getProducts(idNum));
                    }
                }
            }else {
                long idNum=0;
                if (value!=null){
                    idNum=Long.parseLong(value);
                    productList.add(productMapper.getProducts(idNum));
                }
            }
            request.setAttribute("recentProducts",productList);
        }
    }
}
